import { useEventListener } from "@vueuse/core";
import { isFunction } from "@pureadmin/utils";
import { Directive, type DirectiveBinding, h, createApp } from "vue";
import Secondarypassword from "../../components/Secondarypassword/index.vue"

let container, el;
const open = (callback) => {
  container = document.createElement('div');
  // 创建 虚拟dom
  const messageVNode = h(Secondarypassword, {
    callback,
    destroy,
  });
  // 将虚拟dom渲染到 container dom 上
  el = createApp(messageVNode);
  el.mount(container)
  // 最后将 container 追加到 body 上
  document.body.appendChild(container)
}

/**
  * 销毁弹窗
  */
const destroy = () => {
  // 卸载一个已挂载的应用实例
  el.unmount();
  document.body.removeChild(container);
}
/** 打开二次密码弹框 */
export const btnPassword: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    const { beforePermission, clickEvent } = value;
    // 使用指令，可以传递两个回调函数或者一个
    useEventListener(el, 'click', () => {
      if (isFunction(value)) {
        open(value);
      } else {
        if (beforePermission() || !isFunction(beforePermission)) {
          open(clickEvent);
        }
      }
    });
  },

};
